package com.etong.citymap.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.log.LogUtil;

/**
 * 相机拍照
 */
public class CameraActivity extends Activity implements OnClickListener {
	private Camera camera;
	private Camera.Parameters parameters = null;
	ArrayList<String> camernames;
	Button camer_setting;
	PopupWindow popupWindow;
	RelativeLayout camer_layoutfream;
	ImageView camer_display;
	AudioManager meng = null;
	private MediaPlayer mp;
	private CityApplication cityApplication;
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camer);
		cityApplication = (CityApplication)getApplication();
		SurfaceView surfaceView = (SurfaceView) this
				.findViewById(R.id.surfaceView);
		surfaceView.getHolder()
				.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceView.getHolder().setFixedSize(176, 144); // 设置Surface分辨率
		surfaceView.getHolder().setKeepScreenOn(true);
		surfaceView.getHolder().addCallback(new SurfaceCallback());
		camernames = new ArrayList<String>();
		//Configure.IsFristCamer = false;
		cityApplication.setFristCamer(false);
		meng = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
		init();
		View view = LayoutInflater.from(this).inflate(R.layout.camersettingl,
				null);
		popupWindow = new PopupWindow(view);
		popupWindow.setAnimationStyle(R.style.popwin_anim_style);
		popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
		popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
	}

	void init() {
		camer_setting = (Button) findViewById(R.id.camer_setting);
		camer_setting.setOnClickListener(this);
		camer_layoutfream = (RelativeLayout) findViewById(R.id.camer_layoutfream);
		camer_layoutfream.setOnClickListener(this);
		camer_display = (ImageView) findViewById(R.id.camer_display);
		camer_display.setOnClickListener(this);
	}

	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			display();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	public void btnOnclick(View v) {
		if (camera != null) {
			switch (v.getId()) {
			case R.id.takepicture:
				camera.autoFocus(duijiao);
				break;
			}
		}
	}
	AutoFocusCallback duijiao = new AutoFocusCallback() {

		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			if (success) {
				camera.takePicture(null, null, new MyPictureCallback());
			}
		}

	};

	private final class MyPictureCallback implements PictureCallback {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			try {
				new SaveImage(data); // 保存图片到sd卡中
				playsound();
				Toast.makeText(CameraActivity.this, "拍照成功", Toast.LENGTH_SHORT).show();
				camera.startPreview();
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}
	}

	class SaveImage extends Thread {
		byte[] data;

		public SaveImage(byte[] data) {
			this.data = data;
			start();
		}

		@Override
		public void run() {
			super.run();
			try {
				saveToSDCard(data);
			} catch (Exception e) {
				LogUtil.e(e);
			}

		}

		public void saveToSDCard(byte[] data) throws IOException {
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = format.format(date) + ".jpg";
			File fileFolder = new File(	Environment.getExternalStorageDirectory()+ cityApplication.CameraPath);
			if (!fileFolder.exists()) {
				fileFolder.mkdir();
			}
			camernames.add(filename);
			File jpgFile = new File(fileFolder, filename);
			FileOutputStream outputStream = new FileOutputStream(jpgFile);
			outputStream.write(data);
			outputStream.close();
		}

	}

	private final class SurfaceCallback implements Callback {
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			parameters = camera.getParameters();
			parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
			parameters.setPreviewSize(width, height); // 设置预览大小
			parameters.setPreviewFrameRate(5); // 设置每秒显示4帧
			parameters.setPictureSize(width, height); // 设置保存的图片尺寸
			parameters.setJpegQuality(80); // 设置照片质量
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			try {
				camera = Camera.open();
				camera.setPreviewDisplay(holder);
				camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));
				camera.startPreview();
			} catch (Exception e) {
				LogUtil.e(e);
			}

		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			if (camera != null) {
				camera.release();
				camera = null;
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_CAMERA:
			if (camera != null && event.getRepeatCount() == 0) {
				camera.takePicture(null, null, new MyPictureCallback());
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public static int getPreviewDegree(Activity activity) {
		int rotation = activity.getWindowManager().getDefaultDisplay()
				.getRotation();
		int degree = 0;
		switch (rotation) {
		case Surface.ROTATION_0:
			degree = 90;
			break;
		case Surface.ROTATION_90:
			degree = 0;
			break;
		case Surface.ROTATION_180:
			degree = 270;
			break;
		case Surface.ROTATION_270:
			degree = 180;
			break;
		}
		return degree;
	}

	@Override
	public void onClick(View v) {
		if (camer_setting == v) {
			int[] location = new int[2];
			v.getLocationOnScreen(location);
			popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
					location[1] - 150);
		}
		if (camer_layoutfream == v) {
			popupWindow.dismiss();
		}
		if (camer_display == v) {
			display();
		}

	}

	void display(){
		Intent intent = new Intent(this, CamerDisplayActivity.class);
		intent.putStringArrayListExtra("list", camernames);
		startActivity(intent);
		finish();	
	}
	private void playsound() {
		if(mp==null){
			mp= MediaPlayer.create(this, R.raw.shengyin);
		}
		mp.start();
	}
}